<template>
    <div>
        <div class="desc-editor-box">
            <div class="desc-editor-tool">
                <Button class="tool-button" size="small" @click="openFull">{{
                    $L("全屏")
                }}</Button>
            </div>
            <div v-if="loadIng > 0" class="desc-editor-load">
                <WLoading />
            </div>
            <Editor
                class="desc-editor-content"
                v-model="content"
                v-if="showMini"
                :init="editorMini"
                @onBlur="handleBlur"
            />
            <Modal
                v-model="showFull"
                class="desc-editor-transfer"
                footer-hide
                fullscreen
                transfer
                @on-visible-change="handleClose"
            >
                <div slot="close">
                    <Button type="primary" size="small">{{
                        $L("完成")
                    }}</Button>
                </div>
                <div class="desc-editor-transfer-body">
                    <Editor
                        v-model="content"
                        v-if="showFull"
                        :init="editorFull"
                        @onBlur="handleBlur"
                    />
                </div>
            </Modal>
        </div>
    </div>
</template>

<style lang="scss">
    .desc-editor-box {
        .desc-editor-content {
            img {
                max-width: 100%;
                max-height: 100%;
            }
            &:before {
                left: 8px !important;
                color: #cccccc !important;
            }
        }
    }
    .desc-editor-transfer {
        background-color: #ffffff;
        .tox-toolbar {
            > div:last-child {
                > button:last-child {
                    margin-right: 64px;
                }
            }
        }
        .ivu-modal-header {
            display: none;
        }
        .ivu-modal-close {
            top: 7px;
            z-index: 2;
        }
        .desc-editor-transfer-body {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            padding: 0;
            margin: 0;
            textarea {
                opacity: 0;
            }
            .tox-tinymce {
                border: 0;
                .tox-statusbar {
                    span.tox-statusbar__branding {
                        a {
                            display: none;
                        }
                    }
                }
            }
        }
    }
    </style>
    <style lang="scss" scoped>
    .desc-editor-box {
        position: relative;
        &:hover {
            .desc-editor-tool {
                .tool-button {
                    opacity: 0.9;
                    &:hover {
                        opacity: 1;
                    }
                }
            }
        }
        .desc-editor-tool {
            display: flex;
            flex-direction: row;
            align-items: center;
            position: absolute;
            top: 5px;
            right: 5px;
            z-index: 2;
            .tool-button {
                font-size: 12px;
                opacity: 0;
                transition: all 0.2s;
                margin-left: 5px;
                background-color: #ffffff;
            }
        }
        .desc-editor-load {
            position: absolute;
            right: 5px;
            bottom: 5px;
            z-index: 2;
            width: 16px;
            height: 16px;
        }
    }
    .desc-editor-content {
        position: relative;
        margin: 10px 0 6px;
        border: 2px solid transparent;
        padding: 5px 8px;
        color: #172b4d;
        line-height: 1.5;
        border-radius: 4px;
        min-height: 56px;
        max-height: 182px;
        background: rgba(9, 30, 66, 0.04);
        overflow: auto;
        &:focus {
            box-shadow: 0 0 0 2px rgba(45, 140, 240, .2);
        }
    }
    </style>
<script>
import Editor from "@tinymce/tinymce-vue";
import axios from "axios";
import tinymce from "tinymce/tinymce";
import "tinymce/models/dom";
import "tinymce/themes/silver";
import "tinymce/icons/default";
import "tinymce/plugins/advlist";
import "tinymce/plugins/anchor";
import "tinymce/plugins/autolink";
import "tinymce/plugins/charmap";
import "tinymce/plugins/code";
import "tinymce/plugins/codesample";
import "tinymce/plugins/directionality";
import "tinymce/plugins/image";
import "tinymce/plugins/insertdatetime";
import "tinymce/plugins/link";
import "tinymce/plugins/lists";
import "tinymce/plugins/media";
import "tinymce/plugins/nonbreaking";
import "tinymce/plugins/pagebreak";
import "tinymce/plugins/preview";
import "tinymce/plugins/autoresize"
import "tinymce/plugins/searchreplace";
import "tinymce/plugins/table";
import "tinymce/plugins/visualblocks";
import "tinymce/plugins/visualchars";
import "tinymce/plugins/wordcount";
import "tinymce/plugins/emoticons";
export default {
    name: "DescEditor",
    components: { Editor },
    props: {
        taskid: {
            default: "",
        },
        desc: {
            default: "",
        },
        placeholder: {
            type: String,
            default: "",
        },
    },
    data() {
        return {
            loadIng: 0,
            content: "1231241241",
            submitContent: "",
            editorMini: this.editorOption(false),
            editorFull: this.editorOption(true),
            showMini: false,
            showFull: false,
        };
    },
    created() {},
    mounted() {
        this.loadData((val) => {
            this.submitContent = val;
            this.content = val;
            this.$nextTick(() => {
                this.showMini = true;
            });
        });
    },
    watch: {
    },
    methods: {
        handleClose(visible) {
            if (!visible) {
                this.showMini = true;
                this.showFull = false;
            }
        },
        editorOption(isFull) {
            return {
                language_url: "/tinymce/langs/zh-Hans.js",
                language: "zh-Hans",
                skin_url: "/tinymce/skins/ui/oxide",
                content_css: "/tinymce/skins/content/default/content.css",
                emoticons_database_url: "/tinymce/emoji/emojis.js",
                placeholder: this.placeholder,
                plugins: [
                    "searchreplace",
                    "autolink",
                    "directionality",
                    "visualblocks",
                    "visualchars",
                    "image",
                    "link",
                    "media",
                    "code",
                    "codesample",
                    "table",
                    "charmap",
                    "pagebreak",
                    "nonbreaking",
                    "anchor",
                    "insertdatetime",
                    "advlist",
                    "lists",
                    "wordcount",
                    "preview",
                    "emoticons",
                    "autoresize",
                ],
                inline: !isFull,
                inline_boundaries: false,
                menubar: isFull,
                toolbar: isFull
                    ? "undo redo | bold italic underline strikethrough | fontfamily fontsize blocks | alignleft aligncenter alignright alignjustify | outdent indent |  numlist bullist | forecolor backcolor removeformat | pagebreak | charmap emoticons |  preview save print | insertfile image media template link anchor codesample | ltr rtl"
                    : false,
                toolbar_sticky: true,
                image_advtab: true,
                image_caption: true,
                toolbar_mode: "wrap",
                contextmenu: "forecolor fontsize link image table",
                font_size_formats:
                    "12px 14px 16px 18px 20px 22px 24px 28px 32px 36px 48px 56px 72px",
                font_family_formats:
                    "微软雅黑=Microsoft YaHei,Helvetica Neue,PingFang SC,sans-serif;苹果苹方=PingFang SC,Microsoft YaHei,sans-serif;宋体=simsun,serif;仿宋体=FangSong,serif;黑体=SimHei,sans-serif;Arial=arial,helvetica,sans-serif;Arial Black=arial black,avant garde;Book Antiqua=book antiqua,palatino;",
                line_height_formats: "0.5 0.8 1 1.2 1.5 1.75 2 2.5 3 4 5",
                height: isFull ? 'auto' : 360,
                branding: false,
                resize: false,
                elementpath: true,
                content_style: "img {max-width:100%;}",
                paste_data_images: true,
                images_upload_handler: (blobInfo, progress) =>
                    new Promise((resolve, reject) => {
                        const blob = blobInfo.blob();
                        const data = new FormData();
                        data.append("image", blob);
                        data.append("token", $A.getToken());

                        axios
                            .post($A.apiUrl("system/imgupload"), data, {
                                headers: {
                                    "Content-Type": "multipart/form-data",
                                },
                                onUploadProgress: (progressEvent) => {
                                    progress(
                                        (progressEvent.loaded /
                                            progressEvent.total) *
                                            100
                                    );
                                },
                            })
                            .then((res) => {
                                resolve(res.data.data.url);
                            })
                            .catch((error) => {
                                reject("上传失败，原因：" + error.toString());
                            });
                    }),
                file_picker_callback: (callback, value, meta) => {
                    let filetype, url, filename;
                    switch (meta.filetype) {
                        case "image":
                            filetype = ".jpg, .jpeg, .png, .gif";
                            url = $A.apiUrl("system/imgupload");
                            filename = "image";
                            break;
                        case "media":
                            filetype = ".mp3, .mp4, .mov, .avi";
                        case "file":
                            url = $A.apiUrl("system/fileupload");
                            filename = "files";
                        default:
                    }
                    const input = document.createElement("input");
                    input.setAttribute("type", "file");
                    input.setAttribute("accept", filetype);
                    input.click();
                    input.onchange = (ev) => {
                        const file = ev.target.files[0];
                        const data = new FormData();
                        data.append(filename, file, file.name);
                        data.append("token", $A.getToken());

                        axios
                            .post(url, data, {
                                headers: {
                                    "Content-Type": "multipart/form-data",
                                },
                            })
                            .then((res) => {
                                const data = res.data.data;
                                callback(data.url, {
                                    title: `${data.name}(${data.size}KB)`,
                                });
                            })
                            .catch((error) => {
                                console.error(
                                    "上传失败，原因：" + error.toString()
                                );
                            });
                    };
                },
            };
        },
        loadData(callback) {
            this.loadIng++;
            $A.apiAjax({
                url: "project/task/desc",
                data: {
                    taskid: this.taskid,
                },
                complete: () => {
                    this.loadIng--;
                },
                success: (res) => {
                    if (res.ret === 1) {
                        callback(res.data.desc);
                    } else {
                        callback("");
                    }
                },
            });
        },

        openFull() {
            console.log(this.editorFull)
            this.showMini = false;
            this.showFull = true;
        },

        handleBlur() {
            this.loadIng++;
            setTimeout(() => {
                this.handleSave();
                this.loadIng--;
            }, 300);
        },

        handleSave() {
            if (this.submitContent !== this.content) {
                const bakContent = this.submitContent;
                this.submitContent = this.content;
                //
                this.loadIng++;
                $A.apiAjax({
                    url: "project/task/edit",
                    method: "post",
                    data: {
                        act: "desc",
                        taskid: this.taskid,
                        content: this.submitContent,
                    },
                    complete: () => {
                        this.loadIng--;
                    },
                    error: () => {
                        this.content = bakContent;
                        alert(this.$L("网络繁忙，请稍后再试！"));
                    },
                    success: (res) => {
                        if (res.ret === 1) {
                            $A.triggerTaskInfoListener("desc", res.data);
                            $A.triggerTaskInfoChange(this.taskid);
                            this.$Message.success(res.msg);
                            this.$emit("save-success");
                        } else {
                            this.$Modal.error({
                                title: this.$L("温馨提示"),
                                content: res.msg,
                            });
                            this.content = bakContent;
                        }
                    },
                });
            }
        },
    },
};
</script>
